package com.zch.rpc.core.net.jetty1;


import com.zch.rpc.core.model.RpcRequestModel;
import com.zch.rpc.core.model.RpcResponseModel;
import com.zch.rpc.core.serialize.Serializer;
import com.zch.rpc.core.serialize.impl.HessianSerializer;
import com.zch.rpc.core.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * jetty client
 */
public class JettyClient {
	private static Logger logger = LoggerFactory.getLogger(JettyClient.class);
    Serializer hessianSerializer= Serializer.SerializeEnum.HESSIAN.getSerializer();
	public RpcResponseModel send(RpcRequestModel request,String serverIpPort) throws Exception {
		try {
			// serialize request
			byte[] requestBytes = hessianSerializer.serialize(request);

			// reqURL
			String reqURL=serverIpPort;
			if (reqURL!=null && reqURL.toLowerCase().indexOf("http")==-1) {
				reqURL = "http://" + serverIpPort + "/";	// IP:PORT, need parse to url
			}

			// remote invoke
			byte[] responseBytes = HttpClientUtil.postRequest(reqURL, requestBytes);
			if (responseBytes == null || responseBytes.length==0) {
				RpcResponseModel rpcResponse = new RpcResponseModel();
				rpcResponse.setErrorMsg("Network request fail, RpcResponse byte[] is null");
				return rpcResponse;
            }

            // deserialize response
			RpcResponseModel rpcResponse = (RpcResponseModel) hessianSerializer.deserialize(responseBytes, RpcResponseModel.class);
			return rpcResponse;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			RpcResponseModel rpcResponse = new RpcResponseModel();
			rpcResponse.setErrorMsg("Network request error: " + e.getMessage());
			return rpcResponse;
		}
	}

}
